package com.lijianpo.util.extension.datamasking.ser;

import com.fasterxml.jackson.core.JsonGenerator;
import com.fasterxml.jackson.databind.JsonSerializer;
import com.fasterxml.jackson.databind.SerializerProvider;
import com.lijianpo.util.extension.datamasking.SensitiveType;

import java.io.IOException;

/**
 * @author zhangyang
 * @date 2020/11/2 15:34
 */
public abstract class BaseSensitiveSerializer<T> extends JsonSerializer<T> {

    protected SensitiveType sensitiveType;

    protected int[] keepChars;


    protected BaseSensitiveSerializer(SensitiveType sensitiveType, int[] keepChars) {
        this.sensitiveType = sensitiveType;
        this.keepChars = keepChars;
    }

    /**
     * 执行序列化方法
     *
     * @param value
     * @param gen
     * @param serializers
     * @throws IOException
     */
    @Override
    public abstract void serialize(T value, JsonGenerator gen, SerializerProvider serializers) throws IOException;

    /**
     * 默认的脱敏方法
     *
     * @param value
     * @param gen
     * @throws IOException
     */
    protected void stringSerialize(String value, JsonGenerator gen) throws IOException {
        boolean isDefault = keepChars == null || keepChars.length != 0 && keepChars[0] < 0;
        if (isDefault) {
            gen.writeString(sensitiveType.getStrategy().mask(value, sensitiveType.getParams()));
        } else {
            gen.writeString(sensitiveType.getStrategy().mask(value, keepChars));
        }
    }


}
